package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地区资源控制器
 */
@RestController
@RequestMapping("/regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;
    //引入上下文对象
    @Autowired
    private ServletContext servletContext;
    //查出所有地区
    @GetMapping
    public List<Region> list (){

        return regionService.listAll();
    }


    //查出所有状态为推荐的地区
    @GetMapping("/{state}")
    public List<Region> listByState (@PathVariable Integer state){

        return regionService.listByState(state);
    }

    //根据地区id查出改地区的大攻略和推荐的大攻略
    @GetMapping(value = "/{placeId}/strategy",produces = "text/html;charset=utf-8")
    public void listByRegionIdAndState(StrategyQuery qo, HttpServletResponse response) throws Exception {
        //查出该地区的所有大攻略
        qo.setPageSize(4);
        qo.setState(null);
        PageInfo<Strategy> all = strategyService.query(qo);
        //查出该地区的推荐大攻略
        qo.setState(1);
        qo.setPageSize(0);
        PageInfo<Strategy> hot = strategyService.query(qo);

        //创建FreeMark配置对象
        Configuration freeMark = new Configuration(Configuration.VERSION_2_3_23);
        //配置模板目录
        freeMark.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("template")));
        //设置接收模板的编码格式
        freeMark.setDefaultEncoding("utf-8");
        //找到指定的文件
        Template template = freeMark.getTemplate("template.ftl");
        //把查出来的数据封装到map中
        Map<String,Object> map =new HashMap<String,Object>();
        map.put("all",all);
        map.put("hot",hot);
        //合成数据
        template.process(map,response.getWriter());
    }

    //根据地区id查出改地区的大攻略和推荐的大攻略(分页 第二页开始)
    @GetMapping(value = "/{placeId}/strategy",produces = "application/json;charset=utf-8")
    public PageInfo listByRegionIdAndState(StrategyQuery qo){
        qo.setPageSize(4);
        return strategyService.query(qo);
    }
}
